package com.admin.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 
 *  @author LeiHongyun  2010-10-27 09:49:54
 *
 */
public class FileUtil {

	/**
	 * java�������������ʱ����Ե�������������߳�����֮������
	 * @param p
	 * @return
	 */
	public static int doWaitFor(Process p) {  
		int exitValue = -1; // returned to caller when p is finished
		try {
			InputStream in = p.getInputStream();
			InputStream err = p.getErrorStream();
			boolean finished = false; // Set to true when p is finished
			while (!finished) {
				try {
					while (in.available() > 0) {
						// Print the output of our system call
						Character c = new Character((char) in.read());
						//System.out.print(c);
					}
					while (err.available() > 0) {
						// Print the output of our system call
						Character c = new Character((char) err.read());
						//System.out.print(c);
					}

					// Ask the process for its exitValue. If the process
					// is not finished, an IllegalThreadStateException
					// is thrown. If it is finished, we fall through and
					// the variable finished is set to true.
					exitValue = p.exitValue();
					finished = true;
				} catch (IllegalThreadStateException e) {
					// Process is not finished yet;
					// Sleep a little to save on CPU cycles
					Thread.currentThread().sleep(500);
				}
			}
		} catch (Exception e) {
			// unexpected exception! print it out for debugging...
			System.err.println("doWaitFor();: unexpected exception - "
					+ e.getMessage());
		}

		// return completion status to caller
		return exitValue;
	 }
	
	public static String getFileExt(String fileName) {
		if (fileName == null) {
			return null;
		}
		int i = fileName.lastIndexOf(".");
		if (i == -1) {
			return null;
		}
		return fileName.substring(i + 1, fileName.length());
	}
	
	public static String getFileNameNoExt(String fileName) {
		if (fileName == null) {
			return null;
		}
		int i = fileName.lastIndexOf(".");
		if (i == -1) {
			return null;
		}
		return fileName.substring(0, i);
	}

	public static String getUniqueFileName() {
		return String.valueOf(Calendar.getInstance().getTimeInMillis());
	}

	public static boolean checkIconFileExt(String fileExt) {
		if (!fileExt.equalsIgnoreCase("gif")
				&& !fileExt.equalsIgnoreCase("jpg")
				&& !fileExt.equalsIgnoreCase("png")
				&& !fileExt.equalsIgnoreCase("wbmp")
				&& !fileExt.equalsIgnoreCase("dgif")) {
			return false;
		}
		return true;
	}

	public static boolean checkImageFileExt(String fileExt) {
		if (!fileExt.equalsIgnoreCase("gif")
				&& !fileExt.equalsIgnoreCase("jpg")
				&& !fileExt.equalsIgnoreCase("png")
				&& !fileExt.equalsIgnoreCase("wbmp")
				&& !fileExt.equalsIgnoreCase("dgif")) {
			return false;
		}
		return true;
	}

	public static boolean checkRingFileExt(String fileExt) {
		if (!fileExt.equalsIgnoreCase("mid")
				&& !fileExt.equalsIgnoreCase("amr")
				&& !fileExt.equalsIgnoreCase("mp3")
				&& !fileExt.equalsIgnoreCase("mmf")) {
			return false;
		}
		return true;
	}

	public static boolean checkSoftwareFileExt(String fileExt) {
		if (!fileExt.equalsIgnoreCase("jar")
				&& !fileExt.equalsIgnoreCase("jad")) {
			return false;
		}
		return true;
	}

	public static boolean checkVideoFileExt(String fileExt) {
		if (!fileExt.equalsIgnoreCase("jar")
				&& !fileExt.equalsIgnoreCase("jad")) {
			return false;
		}
		return true;
	}

	public static void dealImage(String inURL, int newWidth, String outURL) {
		try {
			File _file = new File(inURL);
			Image src = javax.imageio.ImageIO.read(_file);
			int width = src.getWidth(null);
			int height = src.getHeight(null);

			BufferedImage tag = new BufferedImage(newWidth, height * newWidth
					/ width, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src, 0, 0, newWidth,
					height * newWidth / width, null);

			FileOutputStream out = new FileOutputStream(outURL);

			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ImageFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getThumbnailName(String imageName) {
		if (imageName == null) {
			return null;
		} else {
			imageName = imageName.substring(0, imageName.lastIndexOf('.') - 1)
					+ "_tn.jpg";
			return imageName;
		}
	}

	public static boolean copyFile(File fromFile, File toFile) {
		try {
			if (!toFile.exists()) {
				toFile.createNewFile();
			}

			FileInputStream fis = new FileInputStream(fromFile);
			FileOutputStream fos = new FileOutputStream(toFile);

			byte[] buf = new byte[1024];
			int len;
			while ((len = fis.read(buf)) > -1) {
				fos.write(buf, 0, len);
			}
			fis.close();
			fos.close();

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public static boolean copyDir(File fromDir, File toDir) {
		if (!fromDir.exists()) {
			return false;
		}

		if (!toDir.exists()) {
			toDir.mkdirs();
		}

		File[] fromFiles = fromDir.listFiles();
		if (fromFiles == null) {
			return true;
		}
		File fromFile = null;
		File toFile = null;

		int len = fromFiles.length;
		for (int i = 0; i < len; i++) {
			fromFile = fromFiles[i];
			toFile = new File(toDir.getAbsolutePath() + "/"
					+ fromFile.getName());
			if (!copyFile(fromFile, toFile)) {
				return false;
			}
		}

		return true;
	}

	public static void writeImage(HttpServletResponse response, String filePath) {
		try {
			InputStream is = new FileInputStream(new File(filePath));
			OutputStream os = response.getOutputStream();
			byte[] buffer = new byte[256];
			int len = -1;
			while ((len = is.read(buffer, 0, buffer.length)) != -1) {
				os.write(buffer, 0, len);
			}
			os.flush();
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void writeImageURL(HttpServletRequest request,
			HttpServletResponse response, String filePath) {
		String file = request.getSession().getServletContext().getRealPath(
				filePath);
		response.setContentType("image/gif");
		writeImage(response, file);
	}
	
	
	/**
	 * create a new Directory
	 * 
	 * @param prmDirectory
	 *          directroy path
	 * @return
	 */
	public static boolean createDirectory(String prmDirectory) {
		File file = new File(prmDirectory);
		if (!file.exists()) {
			return file.mkdirs();
		} else {
			//strErrorInfo = "Directory (" + prmDirectory + ") is exist!";
			System.out.println("Directory (" + prmDirectory + ") is exist!");
			return false;
		}
	}

	/**
	 * create a new file
	 * 
	 * @param strPath
	 *          file path
	 * @param prmFileName
	 *          file name
	 * @return
	 */
	public static boolean createNewFile(String strPath, String prmFileName) {
		createDirectory(strPath);
		File file = new File(strPath + "/" + prmFileName);
		if (!file.exists()) {
			try {
				return file.createNewFile();
			} catch (IOException e) {
				//strErrorInfo = e.toString();
				return false;
			}
		} else {
			//strErrorInfo = "File (" + prmFileName + ") is exist!";
			System.out.println("File (" + prmFileName + ") is exist!");
			return false;
		}
	}

	/**
	 * move directory
	 * 
	 * @param prmSrcDir
	 *          source directroy
	 * @param prmDestDir
	 *          destination directroy
	 * @return
	 */
	public static boolean moveDirectory(String prmSrcDir, String prmDestDir) {
		File srcFile = new File(prmSrcDir);
		File destFile = new File(prmDestDir);
		if (srcFile.exists()) {
			if (destFile.exists()) {
				String srcList[] = srcFile.list();
				for (int i = 0; i < srcList.length; i++) {
					moveDirectory(prmSrcDir + "/" + srcList[i], prmDestDir + "/"
							+ srcList[i]);
				}
				srcFile.delete();
				return true;
			} else {
				return srcFile.renameTo(destFile);
			}
		} else {
			//strErrorInfo = "Src Directory (" + prmSrcDir + ") is not exist!";
			System.out.println("Src Directory (" + prmSrcDir + ") is not exist!");
			return false;
		}
	}

	/**
	 * copy directory
	 * 
	 * @param prmSrcDir
	 *          source directory
	 * @param prmDestDir
	 *          destination directory
	 * @return
	 */
	public static boolean copyDirectory(String prmSrcDir, String prmDestDir) {
		(new File(prmDestDir)).mkdirs();
		File[] file = (new File(prmSrcDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				try {
					FileInputStream input;
					input = new FileInputStream(file[i]);
					FileOutputStream output = new FileOutputStream(prmDestDir + "/"
							+ file[i].getName());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				} catch (IOException e) {
					//strErrorInfo = e.toString();
					e.printStackTrace();
					return false;
				}
			}
			if (file[i].isDirectory()) {
				copyDirectory(prmSrcDir + "/" + file[i].getName(), prmDestDir + "/"
						+ file[i].getName());
			}
		}
		return true;
	}

	/**
	 * copy file
	 * 
	 * @param prmSrcFile
	 *          source file
	 * @param prmDestFile
	 *          destination file
	 * @return
	 */
	public static boolean copyFile(String prmSrcFile, String prmDestFile) {
		File file = new File(prmSrcFile);
		if (file.isFile()) {
			try {
				FileInputStream input;
				input = new FileInputStream(file);
				FileOutputStream output = new FileOutputStream(prmDestFile);
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = input.read(b)) != -1) {
					output.write(b, 0, len);
				}
				output.flush();
				output.close();
				input.close();
			} catch (IOException e) {
				//strErrorInfo = e.toString();
				return false;
			}
		} else {
			//strErrorInfo = "<" + prmSrcFile + "> is not a File!";
			System.out.println("<" + prmSrcFile + "> is not a File!");
			return false;
		}
		return true;
	}

	/**
	 * get file(sub directory) list in the directory
	 * 
	 * @param prmDirectory
	 *          parent directory
	 * @return String[] file(sub directory) list
	 */
	public static String[] getList(String prmDirectory) {
		File file = new File(prmDirectory);
		return file.list();
	}

	/**
	 * delete directory
	 * 
	 * @param prmDirectory
	 *          directory
	 * @return
	 */
	public static boolean deleteDirectory(String prmDirectory) {
		File file = new File(prmDirectory);
		if(file.exists())
		{
			if(file.isDirectory()){
				File[] files=file.listFiles();
				for(int i=0;i<files.length;i++)
				{
					deleteDirectory(files[i].getPath());
				}
			}
			file.delete();
			return true;
		}
		else
		{
			//strErrorInfo = "Directory (" + prmDirectory + ") is not exist!";
			System.out.println("Directory (" + prmDirectory + ") is not exist!");
			return false;
		}
	}
}
